/*
 * Copyright (c) 2013 哈尔滨亿时代数码科技开发有限公司（www.hrbesd.com）. All rights reserved.
 * 
 * HRBESD PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.esd.ps;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.common.util.UsernameAndPasswordMd5;
import com.esd.db.model.VtdParameter;
import com.esd.db.model.VtdZzhConnection;
import com.esd.db.model.manager;
import com.esd.db.model.task;
import com.esd.db.model.user;
import com.esd.db.model.usertype;
import com.esd.db.model.worker;
import com.esd.db.model.workerRecord;
import com.esd.db.service.EmployerService;
import com.esd.db.service.InspectorService;
import com.esd.db.service.ManagerService;
import com.esd.db.service.PackService;
import com.esd.db.service.SalaryService;
import com.esd.db.service.TaskService;
import com.esd.db.service.UserService;
import com.esd.db.service.UserTypeService;
import com.esd.db.service.VtdParameterService;
import com.esd.db.service.VtdZzhConnectionService;
import com.esd.db.service.WorkerRecordService;
import com.esd.db.service.WorkerService;

/**
 * 登录
 * 
 * @author chen
 * 
 */
@Controller
public class LoginController {
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private UserTypeService userTypeService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private EmployerService employerService;
	@Autowired
	private InspectorService InspectorService;
	@Autowired
	private WorkerService workerService;
	@Autowired
	private WorkerRecordService workerRecordService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private PackService packService;
	@Autowired
	private SalaryService salaryService;
	@Autowired
	private VtdParameterService paramService;
	@Autowired
	private VtdZzhConnectionService vzcService;
	/**
	 * 用户名不存在
	 */
	@Value("${MSG_USER_NOT_EXIST}")
	private String MSG_USER_NOT_EXIST;

	/**
	 * 用户不能为空
	 */
	@Value("${MSG_USER_NOT_EMPTY}")
	private String MSG_USER_NOT_EMPTY;

	/**
	 * 密码不能为空
	 */
	@Value("${MSG_PASSWORD_NOT_EMPTY}")
	private String MSG_PASSWORD_NOT_EMPTY;

	/**
	 * 密码错误
	 */
	@Value("${MSG_PASSWORD_NOT_ERROR}")
	private String MSG_PASSWORD_NOT_ERROR;
	/**
	 * 通一个浏览器多账号登录
	 */
	@Value("${MSG_MULTIPLE_LOGIN}")
	private String MSG_MULTIPLE_LOGIN;
	/**
	 * 用户已停用
	 */
	@Value("${MSG_USER_STOP}")
	private String MSG_USER_STOP;

	/**
	 * 登录页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView index() {
		return new ModelAndView("login");
	}

	/**
	 * 退出页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/quit", method = RequestMethod.GET)
	public  ModelAndView quitGet(HttpSession session, HttpServletRequest request) {
		session.removeAttribute(Constants.USER_ID);
		session.removeAttribute(Constants.USER_LVL);
		session.removeAttribute("typeCount");
		session.removeAttribute(Constants.USER_TYPE);
		session.removeAttribute(Constants.ADD_USER_ID);
		session.removeAttribute("aduiting");
		session.removeAttribute("aduited");
		session.removeAttribute("salary");
		session.removeAttribute("uploading");
//		try {
//			ServletContext servletContext = request.getSession().getServletContext();
//			if (servletContext.getAttribute(session.getAttribute(Constants.USER_NAME).toString()) != null) {
//				servletContext.removeAttribute(session.getAttribute(Constants.USER_NAME).toString());
//			}
//		} catch (NullPointerException n) {
//			return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
//		}
		session.removeAttribute(Constants.USER_NAME);

		return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
	}

	/**
	 * 验证用户名是否存在
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/checkUserName", method = RequestMethod.GET)
	@ResponseBody
	public  Map<String, Object> checkUserName(String username) {

		return checkLoginName(username);
	}

	/**
	 * 验证用户名密码,跳转响应页面
	 * 
	 * @param username
	 * @param password
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public  ModelAndView loginPost(String username, String password, String checkCode, RedirectAttributes redirectAttributes, HttpSession session, HttpServletRequest request) {
		if (StringUtils.isBlank(username)) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_NOT_EMPTY);
		}
		if (StringUtils.isBlank(password)) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_PASSWORD_NOT_EMPTY);
		}
		if (StringUtils.isBlank(checkCode)) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "验证码不能为空");
		}
		// 检验用户是否已经登录
//		int m = loginName(username, request);
//		if (m == 0) {
//			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "用户已经登录");
//			return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
//		}
		
		
		user user = userService.getAllUsersByUserName(username);
		if(!checkCode.equals(session.getAttribute("checkCode").toString())){
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "验证码错误!");
		}else if (user == null) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_NOT_EXIST);
		} else {
			if (user.getUserStatus() == false) {
				redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_STOP);
				redirectAttributes.addFlashAttribute(Constants.USER_NAME, username);
				return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
			}
			UsernameAndPasswordMd5 md5 = new UsernameAndPasswordMd5();
			String md5Password = md5.getMd5(username, password);
			//logger.debug("md5Password:{}", md5Password);
			// 密码比较
			if (md5Password.equals(user.getPassword())&&(session.getAttribute(Constants.USER_ID)==null||user.getUserId().intValue()==((int)session.getAttribute(Constants.USER_ID)))) {
				
				session.setAttribute(Constants.USER_NAME, user.getUsername());
				session.setAttribute(Constants.USER_ID, user.getUserId());
				session.setAttribute(Constants.USER_LVL, user.getUserLvl());
				session.setAttribute(Constants.USER_TYPE, user.getUsertype());
				session.setAttribute(Constants.VOICE_NOTE_NOTICE_FLAG, user.getVoiceNoteNoticeFlag());
				session.setAttribute(Constants.NOTICE_FLAG, user.getNoticeFlag());
				session.setAttribute("zzhUserStatus", user.getUserStatus());
				if(user.getUsertype()==6){  //如果审核管理登陆  默认工作组为0
					session.setAttribute(Constants.WORK_GROUP, "0");
				}else{
					session.setAttribute(Constants.WORK_GROUP, user.getWorkGroupCode());					
				}
				usertype userType = userTypeService.getUserTypeById(user.getUsertype());
				//logger.debug("typeName:{}", userType.getUserTypeNameEnglish());
				String typeName = userType.getUserTypeNameEnglish();
				if (typeName.equals(Constants.MANAGER)) {
					if (managerService.getCountManagerIdByUserId(user.getUserId()) == 0) {
						return new ModelAndView(Constants.MANAGER + Constants.SLASH + Constants.MANAGER + Constants.UNDERLINE + Constants.ADD, Constants.USER_REGISTED, 0);
					}
				} else if (typeName.equals(Constants.EMPLOYER)) {
					if (employerService.getCountEmployerIdByUserId(user.getUserId()) == 0) {
						return new ModelAndView(Constants.MANAGER + Constants.SLASH + Constants.EMPLOYER + Constants.UNDERLINE + Constants.ADD, Constants.USER_REGISTED, 0);
					}
				} else if (typeName.equals("inspector")) {
					if (InspectorService.getCountInspectorIdByUserId(user.getUserId()) == 0) {
						return new ModelAndView(Constants.MANAGER + Constants.SLASH + "inspector" + Constants.UNDERLINE + Constants.ADD, Constants.USER_REGISTED, 0);
					}

				} else if (typeName.equals("inspectorManager")) {
					if (InspectorService.getCountInspectorIdByUserId(user.getUserId()) == 0) {
						return new ModelAndView(Constants.MANAGER + Constants.SLASH + "inspector" + Constants.UNDERLINE + Constants.ADD, Constants.USER_REGISTED, 0);
					}

				} else if (typeName.equals(Constants.WORKER)) {
					if (workerService.getCountWorkerIdByUserId(user.getUserId()) == 0) {
						return new ModelAndView(Constants.MANAGER + Constants.SLASH + Constants.WORKER + Constants.UNDERLINE + Constants.ADD, Constants.USER_REGISTED, 0);
					}
				}
				return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.SECURITY + Constants.SLASH + typeName);

			} else {
				if(!(md5Password.equals(user.getPassword()))){
					redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_PASSWORD_NOT_ERROR);
				}else if(session.getAttribute(Constants.USER_ID)!=null&&user.getUserId().intValue()!=((int)session.getAttribute(Constants.USER_ID))){
					redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_MULTIPLE_LOGIN);
				}
				
			}
		}
		redirectAttributes.addFlashAttribute(Constants.USER_NAME, username);
		redirectAttributes.addFlashAttribute(Constants.USER_PASSWORD, password);
		return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
	}

	/**
	 * 登录检测是否有过时的任务
	 * 超时
	 * 
	 * @param request
	 */
	@RequestMapping(value = "/checkOldTask", method = RequestMethod.POST)
	public void  checkOldTaskPOST(HttpServletRequest request) {
		List<workerRecord> workerRecordList = workerRecordService.getDoingTask();
		SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATETIME_FORMAT);
		if (workerRecordList.isEmpty() == false || workerRecordList != null) {
			for (Iterator<workerRecord> iterator = workerRecordList.iterator(); iterator.hasNext();) {
				workerRecord workerRecord = (workerRecord) iterator.next();
				Date begin, end;
				int m = 0;
				try {
					begin = sdf.parse(sdf.format(workerRecord.getTaskDownTime()));
					end = sdf.parse(sdf.format(new Date()));
					long between = (end.getTime() - begin.getTime());// 毫秒
					long packLockTime = workerRecord.getTaskLockTime();
					//logger.debug("时间差:{}", (packLockTime - between));
					if ((packLockTime - between) == 0 || (packLockTime - between) < 0) {
						// 更新worker_record表
						workerRecord update = new workerRecord();
						update.setTaskStatu(2);// 2表示任务已过时
						update.setTaskEffective(0);
						update.setTaskOverTime(new Date());//
						update.setRecordId(workerRecord.getRecordId());
						StackTraceElement[] items = Thread.currentThread().getStackTrace();
						update.setUpdateMethod(items[1].toString());
						m = workerRecordService.updateByPrimaryKeySelective(update);
						if(m>0){
							// 更新task表
							task task = new task();
							task.setWorkerId(0);
							task.setTaskMarkTime(0.00);
							task.setTaskId(workerRecord.getTaskId());
							task.setTaskUpload(false);
							StackTraceElement[] item = Thread.currentThread().getStackTrace();
							task.setUpdateMethod(item[1].toString());
							taskService.updateByTaskId(task);
						}
//						packWithBLOBs pack = new packWithBLOBs();
//						pack.setPackStatus(0);
//						pack.setPackId(workerRecord.getPackId());
//						packService.updateByPrimaryKeySelective(pack);

						// 删除任务的下载备份
						String url = request.getSession().getServletContext().getRealPath(Constants.SLASH);
						File fold = new File(url + Constants.WORKERTEMP);
						if (fold.exists()) {
							File zipFile = new File(url + Constants.SLASH + workerRecord.getDownPackName());
							if (zipFile.exists()) {
								zipFile.delete();
							}
						}
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		//调用释放初审被退回超时未修改完成任务的方法
		this.releaseModifyUncompletedTasks();
	}

	/**
	 * 检测用户名
	 * 
	 * @param username
	 * @return
	 */
	public Map<String, Object> checkLoginName(String username) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(username)) {
			user user = userService.getAllUsersByUserName(username);
			if (user == null) {
				map.clear();
				map.put(Constants.MESSAGE, MSG_USER_NOT_EXIST);
				map.put(Constants.REPLAY, Constants.ZERO);
				return map;
			}
			if (user.getUserStatus() == false) {
				map.clear();
				map.put(Constants.MESSAGE, MSG_USER_STOP);
				map.put(Constants.REPLAY, Constants.ZERO);
				return map;
			}
			map.clear();
			map.put(Constants.REPLAY, Constants.ONE);
		}
		return map;
	}
	/**
	 * 检测用户是否已经登录了
	 * @param loginName
	 * @param request
	 * @return
	 */
	public int loginName(String loginName, HttpServletRequest request) {
		ServletContext servletContext = request.getSession().getServletContext();
		if (servletContext.getAttribute(loginName) == null) {
			servletContext.setAttribute(loginName, loginName);
			return 1;
		}
		return 0;
	}
	/**
	 * 周榜,月榜
	 * @return
	 */
	@RequestMapping(value = "/moneyList", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> moneyListPost() {
		Map<String, Object> map = new HashMap<String, Object>();
		//得到今天星期
		Calendar cal = Calendar.getInstance();
	    cal.setTime(new Date());  
	    int week = cal.get(Calendar.DAY_OF_WEEK);
	    //得到月份
	    if(week == 7){
	    	week = 0;
	    }
	    //logger.debug("week:{}",week);
	    //日期范围计算
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  // 创建(日历)格式化
	    GregorianCalendar gc = new GregorianCalendar();
	    // 格式化当前日期
	    gc.setTime(new Date());
	    // 在当前日期上减
	    gc.add(5, -week);
	    // 
	    String beginDate = sdf.format(gc.getTime());
	    String endDate = sdf.format(new Date());
	    SimpleDateFormat sdf1 = new SimpleDateFormat("MMdd");
	    String beginDate1 = sdf1.format(gc.getTime());
	    String endDate1 = sdf1.format(new Date());
	    //logger.debug("beginDate:{},endDate:{}",beginDate,endDate);
	    manager manager = managerService.selectByPrimaryKey(1);
	    List<Map<String, Object>> monthList = salaryService.getMoneyList("","", endDate);
	    List<Map<String, Object>> weekList = salaryService.getMoneyList(beginDate,endDate,"");
	    List<Map<String, Object>> totleList = salaryService.getMoneyList("","","");
	   
	    map.put("salary", manager.getSalary());
	    map.put("monthList", monthList);
	    map.put("weekList", weekList);
	    map.put("totleList", totleList);
	    map.put("weekDate",beginDate1+"-"+endDate1);
	    return map;
	}
	/**
	 * 总人数,总金额,任务总量,今日金额
	 * @return
	 */
	@RequestMapping(value = "/datas", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> datasPost() {
		Map<String, Object> map = new HashMap<String, Object>();
		int peopleCountTotle = workerService.getWorkerCount();
		double moneyTotle = 31701234.00;
		try{
			if(salaryService.getMoneyTotle(0) != null){
				moneyTotle = moneyTotle + salaryService.getMoneyTotle(0);
			}
		}catch(NullPointerException n){
			
		}
		
		int taskCountTotle = taskService.getWorkerIdZeroCountByPackId(0);
		int taskCount = taskService.getCountTaskDoing(9);//登录页面查询全部任务数
		double moneyToday = 0.00;
		try{
			moneyToday = salaryService.getMoneyTotle(1);
		}catch(NullPointerException n){
			 moneyToday = 0.00;
		}	
		BigDecimal b = new  BigDecimal(moneyTotle/18);  
		moneyTotle = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		
		BigDecimal b1 = new  BigDecimal(moneyToday/18);  
		moneyToday = b1.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

	    map.put("peopleCountTotle", peopleCountTotle);
	    map.put("moneyTotle", moneyTotle);
	    map.put("taskCountTotle", (taskCountTotle + 28761234));
	    map.put("taskCount", taskCount);
	    map.put("moneyToday", moneyToday);
	    return map;
	}
	
	private void releaseModifyUncompletedTasks(){
		List<VtdParameter> outsourcerCodeList = paramService.selectParamByType(Constants.OUTSOURCER_CODES);  //外包商组代码  数据库中只存一条信息  	
		VtdParameter param = outsourcerCodeList.get(0);
    	String[] outsourcerCodes = param.getParamValue().split(",");
    	//查询初审待修改信息
    	long nowTimeMsec = new Date().getTime();  //现在时间的毫秒数
    	List<Map<String,Object>> waitingModifyList = workerRecordService.queryWaitingModifyList(outsourcerCodes);
    	if(!waitingModifyList.isEmpty()){
    		List<String> releaseSendBackUUIDs = new ArrayList<String>();
    		List<String> workGroupCodes = new ArrayList<String>();
    		for (Map<String, Object> m1 : waitingModifyList) {
    			Date sendbackDate = (Date)m1.get("sendBackTime");
    			long endMsec = sendbackDate.getTime()+Long.parseLong(m1.get("timeLimit").toString());
    			if(endMsec <= nowTimeMsec){//超时
    				releaseSendBackUUIDs.add(m1.get("sendBackUUID").toString());
    				if(!workGroupCodes.contains(m1.get("workGroupCode").toString())){
    					workGroupCodes.add(m1.get("workGroupCode").toString());
    				}
    			}
    		}
    		//释放超时为修改完成的任务
    		int intFlag = 0;
    		if(!releaseSendBackUUIDs.isEmpty()){
    			intFlag = workerRecordService.releaseTasksBySendBackUUIDs(releaseSendBackUUIDs);
    			if(intFlag == 1){
    				//将已经释放过没有被退回修改任务的用户组解除下载任务锁定
    				workerRecordService.workGroupDownloadUnlock(workGroupCodes);
    			}
    		}else{
    			intFlag = 3;
    		}
    		if(intFlag==1){  //临时日志输出
    			logger.error("超时任务释放成功");
    		}else if(intFlag == 3){
    			logger.error("无需要释放的任务");
    		}else{
    			logger.error("超时任务释放失败: ___"+intFlag);
    		}
    	}
	}
	
	/**
	 * zonlolo 请求方法   传过来的用户不存在的话 新建用户和worker然后登陆  已经存在的直接登陆
	 * @param userId  zonlolo的userId
	 * @param loginName   登陆名
	 * @param realName    真是姓名
	 * @param deformityCard   残疾人证号 
	 * @param mobile    手机号
	 * @param timeStamp 时间戳
	 * @param dataSignature 加密字符串
	 * @return
	 */
	@RequestMapping(value = "/vtdLoginRequest", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView vtdLoginRequest(HttpSession session, String userId, String loginName, String realName, String deformityCard,
			String mobile, String timeStamp, String dataSignature) {
		//zzh姓名转码
		String realNameUtf8 = "";
		try {
			realNameUtf8 = new String(realName.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//对比加密  不匹配返回错误页面
		String MD5Key = "userId=" + userId + "&loginName=" + loginName + "&realName=" + realNameUtf8
				+ "&deformityCard=" + deformityCard + "&mobile=" + mobile+ "&timeStamp=" + timeStamp;
		String MD5 = LoginController.getMD5(MD5Key);
		if(!MD5.toUpperCase().equals(dataSignature)){
			return new ModelAndView("/zzhConncetError");  //错误页面
		}
		// 在用户名之前添加 zzh_ 标记然后检查用户名
		String userName = "zzh_"+loginName;
		user u = userService.getAllUsersByUserName(userName);
		// 如果不存在 新增user 设置默认密码 和worker
		if(u==null){
			VtdParameter param = paramService.getParamValueByParamTypeAndParamName(Constants.WORK_GROUP,"众智汇用户组");  //如果没有需要手动添加
			String workGroupCode = param.getParamValue();
			String password = "123qwe";
			//装填user并保存
			user user1 = new user();
			user1.setUsername(userName);
			UsernameAndPasswordMd5 md5 = new UsernameAndPasswordMd5();
			String md5Password = md5.getMd5(userName, password);
			user1.setPassword(md5Password);
			user1.setUsertype(4);
			StackTraceElement[] items = Thread.currentThread().getStackTrace();
			user1.setCreateMethod(items[1].toString());
			user1.setCreateId(0); //默认为0
			user1.setWorkGroupCode(workGroupCode);
			user1.setCreateTime(new Date());
			user1.setVersion(1);
			user1.setUserLvl(1);
			user1.setUserStatus(false);    //账号设置为不可用  这样登录过去可以限制下载
			int insertedUserId = userService.insertSelectiveReturnUserId(user1);
//			System.out.println("userid = :   "+user1.getUserId());
			
			//装填worker并保存
			String workerDeformityCard = "";
			String workerIdCard = "";
			if(deformityCard.equals("null")){
				String uuid32 = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
				workerIdCard = uuid32.substring(0,18);
				workerDeformityCard = uuid32.substring(0,20);
			}else{
				workerDeformityCard = deformityCard;
				workerIdCard = deformityCard.substring(0, 18);
			}
			worker worker = new worker();
			worker.setUserId(insertedUserId);
			worker.setWorkerDisabilityCard(workerDeformityCard);
			worker.setWorkerIdCard(workerIdCard);
			worker.setWorkerPhone(mobile);
			worker.setWorkerRealName(realNameUtf8);
			worker.setWorkGroupCode(workGroupCode);
			worker.setCreateId(0);
			worker.setCreateTime(new Date());
			worker.setCreateMethod(items[1].toString());
			worker.setVersion(1);
			int insertedWorkerId = workerService.insertSelectiveReturnWorkerId(worker);
			
//			System.out.println("workerid :  "+insertedWorkerId);
			//保存连接信息
			VtdZzhConnection vzc = new VtdZzhConnection();
			String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
			vzc.setId(uuid);
			vzc.setRealName(realNameUtf8);
			vzc.setVtdUserId(insertedUserId);
			vzc.setVtdUserName(userName);
			vzc.setVtdWorkerId(insertedWorkerId);
			vzc.setZzhLoginName(loginName);
			vzc.setZzhUserId(userId);
			vzc.setCreateTime(new Date());
			vzcService.insertVtdZzhConnection(vzc);
//			System.out.println(vzc);
			u = user1;
		}
//http://192.168.170.108:8080/ps/vtdLoginRequest?userId=bffd8be080964e2cb1c1c9986e6f3f0d&loginName=testzyc&realName=%E5%BC%A0%E5%BD%A6%E8%B6%85&deformityCard=null&mobile=null&timeStamp=1508224492017&dataSignature=3F92A3B6BDEC53F36B788494BEDF6D7D
		
		// 跳转到工作者页面   添加状态未正式开通该功能点击下载任务 提示联系客服		
		session.setAttribute(Constants.USER_NAME, u.getUsername());
		session.setAttribute(Constants.USER_ID, u.getUserId());
		session.setAttribute(Constants.USER_LVL, u.getUserLvl());
		session.setAttribute(Constants.USER_TYPE, u.getUsertype());
		session.setAttribute(Constants.VOICE_NOTE_NOTICE_FLAG, u.getVoiceNoteNoticeFlag());
		session.setAttribute(Constants.NOTICE_FLAG, u.getNoticeFlag());
		session.setAttribute("zzhUserStatus", u.getUserStatus());
		session.setAttribute(Constants.WORK_GROUP, u.getWorkGroupCode());					
		
		return new ModelAndView("redirect:security/worker");  //错误页面
	}
	
	public static String getMD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];
		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
	
}
